#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
验证完成检测机制修复的代码逻辑
不需要运行实际的Milvus连接，仅验证代码逻辑正确性
"""

import ast
import inspect

def validate_completion_fix():
    """验证完成检测修复的代码逻辑"""
    print("🔍 验证完成检测机制修复")
    print("=" * 50)
    
    # 读取修复后的代码
    try:
        with open('tools/QueuedFileSearchTools.py', 'r', encoding='utf-8') as f:
            source_code = f.read()
        
        # 解析AST
        tree = ast.parse(source_code)
        
        # 检查关键修复点
        checks = {
            'scan_completed_flag': False,
            'processing_completed_flag': False,
            'progress_monitor_break': False,
            'all_workers_finished_method': False,
            'monitor_thread_wait': False
        }
        
        # 检查Progress类的完成标志
        for node in ast.walk(tree):
            if isinstance(node, ast.ClassDef) and node.name == 'Progress':
                for item in node.body:
                    if isinstance(item, ast.AnnAssign) and hasattr(item.target, 'id'):
                        if item.target.id == 'scan_completed':
                            checks['scan_completed_flag'] = True
                            print("✅ 找到 scan_completed 标志")
                        elif item.target.id == 'processing_completed':
                            checks['processing_completed_flag'] = True
                            print("✅ 找到 processing_completed 标志")
            
            # 检查_progress_monitor方法中的break逻辑
            elif isinstance(node, ast.FunctionDef) and node.name == '_progress_monitor':
                for stmt in ast.walk(node):
                    if isinstance(stmt, ast.Break):
                        checks['progress_monitor_break'] = True
                        print("✅ 找到 _progress_monitor 中的 break 语句")
            
            # 检查_all_workers_finished方法
            elif isinstance(node, ast.FunctionDef) and node.name == '_all_workers_finished':
                checks['all_workers_finished_method'] = True
                print("✅ 找到 _all_workers_finished 方法")
            
            # 检查wait_completion方法中的monitor_thread等待
            elif isinstance(node, ast.FunctionDef) and node.name == 'wait_completion':
                code_str = ast.unparse(node)
                if 'monitor_thread' in code_str and 'join' in code_str:
                    checks['monitor_thread_wait'] = True
                    print("✅ 找到 wait_completion 中的监控线程等待逻辑")
        
        # 验证结果
        print("\n📊 验证结果:")
        all_passed = True
        for check_name, passed in checks.items():
            status = "✅" if passed else "❌"
            print(f"   {status} {check_name}: {'通过' if passed else '未通过'}")
            if not passed:
                all_passed = False
        
        print(f"\n{'🎉' if all_passed else '⚠️'} 总体验证: {'所有检查通过' if all_passed else '部分检查未通过'}")
        
        # 检查关键逻辑流程
        print("\n🔄 关键逻辑流程验证:")
        print("1. 文件扫描线程在完成后设置 scan_completed = True")
        print("2. 进度监控线程检查 scan_completed && _all_workers_finished()")
        print("3. 条件满足时设置 processing_completed = True 并 break")
        print("4. wait_completion 等待所有线程包括监控线程完成")
        print("5. 监控停止，不再产生进度输出")
        
        return all_passed
        
    except Exception as e:
        print(f"❌ 验证过程中出错: {e}")
        return False


def check_key_code_sections():
    """检查关键代码段的实现"""
    print("\n🧮 检查关键代码段:")
    
    try:
        with open('tools/QueuedFileSearchTools.py', 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # 查找关键代码段
        key_sections = {
            'scan_completion_marking': False,
            'progress_monitor_completion_check': False,
            'worker_finished_check': False
        }
        
        for i, line in enumerate(lines, 1):
            # 检查扫描完成标记
            if 'self.progress.scan_completed = True' in line:
                key_sections['scan_completion_marking'] = True
                print(f"✅ 第{i}行: 找到扫描完成标记设置")
            
            # 检查进度监控完成检查
            if 'self.progress.scan_completed and self._all_workers_finished()' in line:
                key_sections['progress_monitor_completion_check'] = True
                print(f"✅ 第{i}行: 找到进度监控完成检查逻辑")
            
            # 检查工作线程完成检查
            if 'worker.is_alive()' in line:
                key_sections['worker_finished_check'] = True
                print(f"✅ 第{i}行: 找到工作线程状态检查")
        
        print(f"\n关键代码段验证: {sum(key_sections.values())}/{len(key_sections)} 通过")
        
        return all(key_sections.values())
        
    except Exception as e:
        print(f"❌ 代码段检查出错: {e}")
        return False


def main():
    """主验证函数"""
    print("完成检测机制修复验证")
    print("验证修复是否解决了'目录扫描完成后任务还在不停输出'的问题")
    print()
    
    # 运行验证
    logic_ok = validate_completion_fix()
    code_ok = check_key_code_sections()
    
    print("\n" + "=" * 60)
    print("📋 验证总结:")
    
    if logic_ok and code_ok:
        print("🎉 修复验证通过!")
        print("   - 所有完成标志已正确添加")
        print("   - 进度监控停止逻辑已实现")
        print("   - 工作线程完成检测已添加")
        print("   - 监控线程等待机制已完善")
        print()
        print("✅ 修复应该能解决用户报告的问题:")
        print("   当所有目录遍历迭代完成后，停止扫描和消费者队列")
        
    else:
        print("⚠️ 修复验证未完全通过，可能需要进一步检查")
    
    print("\n💡 使用建议:")
    print("   1. 用小量测试数据验证修复效果")
    print("   2. 观察日志确认'所有处理任务已完成'消息")
    print("   3. 确认进度输出在扫描完成后停止")


if __name__ == "__main__":
    main()